package com.jpscloud.admin.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jpscloud.common.constants.StatusCode;
import com.jpscloud.common.vo.ResponseService;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * @ClassName: LoglevelController
 * @Description: log日志级别控制类
 * @author: Kitty
 * @date: 2018年10月28日 下午6:42:22
 *
 */
@RestController
@RequestMapping(value = "/loglevel")
@Api(value = "系统日志级别controller", tags = { "系统日志级别操作接口" })
public class LoglevelController {

	private final Logger log = LoggerFactory.getLogger(getClass());

	@ApiOperation(value = "查询日志级别", notes = "根据根目录查询日志级别")
	@ApiImplicitParam(name = "package", value = "日志根路径", required = true, dataType = "java.lang.String", defaultValue = "root")
	@GetMapping(value = "/getLoglevel")
	public ResponseService<Level> getLoglevel(@RequestParam(value = "package", required = true) String packageName)
			throws Exception {
		ResponseService<Level> result = new ResponseService<>();
		try {
			LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
			result.setData(loggerContext.getLogger(packageName).getLevel());
		} catch (Exception e) {
			result.setStatus(StatusCode.SYSTEM_EXCEPTION);
			result.setMessage(e.getMessage());
			log.error("LoglevelController->getLoglevel exception.", e);
		}
		return result;
	}

	/**
	 * logback动态修改包名的日志级别
	 * 
	 * @param level
	 *            日志级别
	 * @param packageName
	 *            包名
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "修改日志级别", notes = "根据根目录修改日志级别")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loglevel", value = "日志级别:trace-->debug-->info-->warn-->error-->fatal", required = true, dataType = "java.lang.String"),
			@ApiImplicitParam(name = "package", value = "日志根路径", required = true, dataType = "java.lang.String", defaultValue = "root") })
	@PostMapping(value = "/{loglevel}")
	public String loglevel(@PathVariable("loglevel") String logLevel,
			@RequestParam(value = "package", required = true) String packageName) throws Exception {
		// trace --> debug --> info --> warn --> error -->fatal
		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		loggerContext.getLogger(packageName).setLevel(Level.valueOf(logLevel));
		return "ok";
	}
}
